const app = getApp();
const util = require('../../utils/util.js');
const api = require('../../config/api.js');
var cropper;
Page({
  data: {
    id: 0,
    loading: 0,
    photoArray: [],
    textArray: [],
    bgImgPath: "",
    // 画布的信息
    canvasImgInfo: {
      canvasW: 0,
      canvasH: 0,
      path: ""
    },
    successImg: '',
    showCanvas: false,
    leadImg: "",
    productInfo: {},
    // 是否显示裁剪
    isShowCrop: false,
    // textarea是否隐藏
    isHiddenTextarea: false
  },

  onShow: function () {
  },
  onLoad: function (options) {
    let info = wx.getSystemInfoSync();
    let sysHeight = info.windowHeight - 100;
    this.setData({
      id: options.id,
      sysHeight: sysHeight,
      loading: 0
    });
    this.getDiyInfo(options.id);
  },
  // 获取详情
  getDiyInfo(id) {
    let that = this;
    util.requestApi(api.customInfo, {
      customID: id
    }).then(function (res) {
      if (res.code == 200) {
        let obj = {};
        obj.price = res.content.app_product.price;
        obj.productName = res.content.app_product.productName;
        obj.productID = res.content.productID;
        obj.minNum = res.content.minNum;
        that.setData({
          photoArray: res.content.photoArray,
          textArray: res.content.textArray,
          bgImgPath: res.content.content,
          leadImg: res.content.lead,
          productInfo: obj,
          loading: 1
        });
        that.getRelated();
      }
    })
  },
  // 获取相关信息
  getRelated() {
    let that = this;
    let bgPath = that.data.bgImgPath;
    this.getImgInfo(bgPath).then(res => {
      let canvasImgInfo = that.data.canvasImgInfo;
      canvasImgInfo.canvasW = res.width;
      canvasImgInfo.canvasH = res.height;
      canvasImgInfo.path = res.path;
      that.setData({
        canvasImgInfo: canvasImgInfo,
        loading: 1
      });
    })
  },
  // 封装方法获取图片的信息
  getImgInfo(src) {
    return new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: src,
        success(res) {
          resolve(res);
        }
      });
    });
  },
  //上传图片
  upload: function (e) {
    let index = e.currentTarget.dataset.index,
      photoArray = this.data.photoArray,WHRatio=(photoArray[index].upW / photoArray[index].upH).toFixed(4);
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 上传成功后跳转 裁剪
        let src = res.tempFilePaths[0];
        // 设置标签属性
        that.setData({
          // 裁剪的图片index
          cropperImgIndex: index,
          isHiddenTextarea: true,
          // 从图片选择界面传原图临时文件地址给src
          cropperSrc: src,
          // 设置设置裁剪框的高度
          aspectHeight:200/WHRatio,
          // 设置是否等比缩放
          isProportion: true,
          // 是否显示裁剪
          isShowCrop: true
        });
        cropper = that.selectComponent("#image-cropper");
      }
    })
  },
  cropperload(){
    cropper.imgReset();
  },
  cropperFinish() {
    let that = this;
    cropper.getImg((obj) => {
      let i = this.data.cropperImgIndex,
        photoArray = that.data.photoArray;
      photoArray[i].imgPath = obj.url;
      that.setData({
        photoArray: photoArray,
        isShowCrop: false,
        isHiddenTextarea: false,
      });
    });
  },
  // 取消图片裁剪
  cancelCropper() {
    this.setData({
      isShowCrop: false,
      isHiddenTextarea: false,
    });
  },
  //删除图片
  deleteImg(e) {
    let index = e.currentTarget.dataset.index;
    var that = this;
    let photoArray = that.data.photoArray;
    photoArray[index].imgPath = "";
    that.setData({
      photoArray: photoArray
    });
  },
  synthesis() { // 合成图片
    let that = this;
    const maskCanvas = wx.createCanvasContext('maskCanvas');
    maskCanvas.font = 'normal normal 20px cursive';
    let photoArray = that.data.photoArray;
    let textArray = that.data.textArray;
    let canvasImgInfo = that.data.canvasImgInfo;
    maskCanvas.save();
    // maskCanvas.beginPath(); //给画布画白底 可以不写
    // maskCanvas.setFillStyle('#f00');
    // maskCanvas.fillRect(0, 0, canvasImgInfo.canvasW, canvasImgInfo.canvasH);
    // maskCanvas.closePath();
    // maskCanvas.stroke();
    maskCanvas.drawImage(canvasImgInfo.path, 0, 0, canvasImgInfo.canvasW, canvasImgInfo.canvasH);
    for (let i = 0; i < photoArray.length; i++) {
      if (photoArray[i].photoType == 1) {
        maskCanvas.arc(photoArray[i].upL + photoArray[i].upW / 2, photoArray[i].upT + photoArray[i].upH / 2, photoArray[i].upW / 2, 0, 2 * Math.PI); //绘制圆圈
        maskCanvas.clip();
        maskCanvas.drawImage(photoArray[i].imgPath, photoArray[i].upL, photoArray[i].upT, photoArray[i].upW, photoArray[i].upH);
        maskCanvas.restore();
      } else {
        maskCanvas.drawImage(photoArray[i].imgPath, photoArray[i].upL, photoArray[i].upT, photoArray[i].upW, photoArray[i].upH);
      }
    }
    for (let i = 0; i < textArray.length; i++) {
      maskCanvas.setFillStyle('#000000');
      maskCanvas.setFontSize(textArray[i].textSize);
      let s = textArray[i].textValue; //要画的字符串
      let wInter = textArray[i].textInterval; //文字的宽间隔
      let hInter = textArray[i].textHInterval; //文字的高间隔
      let cWidth = textArray[i].textW; //要画文字的区域宽度
      let cHeight = textArray[i].textH; //要画文字的区域宽度
      let L = textArray[i].textL; //初始左边距
      let T = textArray[i].textT; //初始上边距
      let lastSubStrIndex = 0; //每次开始截取的字符串的索引
      if (textArray[i].textType === 0) {
        let colFontNum = Math.floor(cHeight / (textArray[i].textSize + hInter));
        let cols = Math.ceil(s.length / colFontNum); //所需列数
        if (cols > 1) {
          wInter = wInter + wInter / (cols - 1);
        }
        for (let r = 0; r < cols; r++) {
          T = textArray[i].textT;
          let l = L + (textArray[i].textSize + wInter) * r;
          let rowText = s.substring(lastSubStrIndex, colFontNum * (r + 1));
          lastSubStrIndex = colFontNum * (r + 1);
          for (let j = 0; j < rowText.length; j++) {
            maskCanvas.fillText(rowText[j], l, T);
            T = T + textArray[i].textSize + hInter;
          }
        }
      } else {
        let rowFontNum = Math.floor(cWidth / (textArray[i].textSize + wInter));
        let rows = Math.ceil(s.length / rowFontNum); //所需行数
        if (rowFontNum > 1) {
          wInter = wInter + wInter / (rowFontNum - 1);
        }
        for (let r = 0; r < rows; r++) {
          L = textArray[i].textL;
          let t = T + (textArray[i].textSize + hInter) * r;
          let rowText = s.substring(lastSubStrIndex, rowFontNum * (r + 1));
          lastSubStrIndex = rowFontNum * (r + 1);
          for (let j = 0; j < rowText.length; j++) {
            maskCanvas.fillText(rowText[j], L, t);
            L = L + textArray[i].textSize + wInter;
          }
        }
      }
    }
    maskCanvas.draw(false, setTimeout(function () {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: canvasImgInfo.canvasW,
        height: canvasImgInfo.canvasH,
        canvasId: 'maskCanvas',
        success: res => {
          that.setData({
            successImg: res.tempFilePath
          });
          that.goRemind();
        },
        fail(err) {
          wx.hideLoading();
          wx.showToast({
            title: '合成失败，请重新上传',
            icon: 'none',
            duration: 2000
          });
        }
      })
    }, 200));
  },
  changeInput(e) {
    let index = e.target.dataset.index;
    let value = e.detail.value;
    let textArray = this.data.textArray;
    // if (value.length <= textArray[index].textMax) {
      textArray[index].textValue = value;
      this.setData({
        textArray: textArray
      });
    // } else {
    //   textArray[index].textValue = value.slice(0, textArray[index].textMax);
    //   this.setData({
    //     textArray: textArray
    //   });
    // }
  },
  openMask() {
    let photoArray = this.data.photoArray;
    let textArray = this.data.textArray;
    let reg = /[()\-+=<>?:"{}|\/'\\[\]……&*（）—— ——\-+={}|《》：【】]/;
    for (let i = 0; i < photoArray.length; i++) {
      if (photoArray[i].imgPath == "") {
        wx.showToast({
          title: `图片${i+1}上传不完整`,
          icon: 'none',
          duration: 2000
        });
        return;
      }
    };
    for (let i = 0; i < textArray.length; i++) {
      if (textArray[i].textValue == "") {
        wx.showToast({
          title: `文本${i+1}输入不完整`,
          icon: 'none',
          duration: 2000
        });
        return;
      } else if (reg.test(textArray[i].textValue)) {
        wx.showToast({
          title: `文本${i+1}禁止使用特殊字符`,
          icon: 'none',
          duration: 2000
        });
        return;
      } else if (textArray[i].textValue.length < textArray[i].textMin) {
        wx.showToast({
          title: `文本${i+1}输入少于${textArray[i].textMin}字符`,
          icon: 'none',
          duration: 2000
        });
        return;
      }else if(textArray[i].textValue.length > textArray[i].textMax){
        wx.showToast({
          title: `文本输入过长`,
          icon: 'none',
          duration: 2000
        });
        return;
      }
    }
    wx.showLoading({
      title: '生成中',
    })
    this.synthesis();
  },
  goRemind() {
    let successImg = this.data.successImg,
      productInfo = this.data.productInfo,
      id = this.data.id;
    wx.hideLoading();
    wx.navigateTo({
      url: '/pages/remind/index?obj=' + JSON.stringify({
        successImg: successImg,
        productInfo: productInfo,
        id: id
      }),
    })
  }
})